package com.zyw.auth.controller;

import com.zyw.auth.common.ILxbAdminRights;
import com.zyw.auth.common.ShiroAuthHelper;
import com.zyw.auth.domain.Administrator;
import com.zyw.auth.model.RightsVo;
import com.zyw.auth.service.AdministratorService;
import com.zyw.common.RespCode;
import com.zyw.common.RespResult;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>后台管理系统-主页</p>
 */
@RestController
@RequestMapping("/admin")
public class AdminHomeController {

    private static final Logger logger = LoggerFactory.getLogger(AdminHomeController.class);
    @Autowired
    private AdministratorService adminService;

    /**
     * 返回未认证JSON信息
     */
    @GetMapping("/unauthorized")
    public RespResult<String> unauthorized() {
        return new RespResult<>(RespCode.ERR_401);
    }

    /**
     * 用户登录
     */
    @PostMapping(value = "/login")
    public RespResult<Object> login(Administrator admin, String uuid, String code,HttpServletRequest request) {
        RespResult<Object> result = new RespResult<>();
        // 1、表单数据有效性校验
        if (admin == null) {
            return result.addError(RespCode.ERR_400);
        }
        if (StringUtils.isBlank(admin.getUserName())) {
            return result.addError(RespCode.ERR_400);
        }
        if (StringUtils.isBlank(admin.getPassword())) {
            return result.addError(RespCode.ERR_400);
        }
        if (StringUtils.isBlank(code) || StringUtils.isBlank(uuid)) {
            return result.addError(RespCode.ERR_400);
        }
        // 2、验证码校验
        if (!adminService.checkCaptcha(uuid, code)) {
            logger.error("登录失败[name=" + admin.getUserName() + "]验证码错误");
            return result.addError("验证码错误");
        }
       
        // 3、校验用户身份
        result = adminService.login(admin, request.getHeader(HttpHeaders.USER_AGENT));
        logger.info("登录成功[name=" + admin.getUserName() + "]");
        return result;
    }


    /**
     * 注销/登出
     */
    @RequestMapping(value = "/logout", method = {RequestMethod.GET, RequestMethod.POST})
    public RespResult<String> logout(HttpServletRequest request) {
        RespResult<String> result = adminService.logout(request.getHeader(HttpHeaders.USER_AGENT));
        logger.info("登出成功");
        return result;
    }

    /**
     * 查询初始菜单（一级菜单 + 【第一个】一级菜单下子菜单
     */
    @GetMapping("/menus/main")
    public RespResult<Map<String, Object>> queryMainMenus() {
        RespResult<Map<String, Object>> result = new RespResult<>();
        Map<String, Object> data = adminService.queryMainMenus();
        return result.addSuccess(data);
    }

    /**
     * 查询二级菜单（包括页面操作权限）
     */
    @GetMapping("/menus/side/{menuPid}")
    public RespResult<Object> querySideMenus(@PathVariable("menuPid") Long menuId) {
        RespResult<Object> result = new RespResult<>();
        if (menuId == null) {
            return result.addError(RespCode.ERR_400);
        }
        List<RightsVo> data = adminService.querySideMenus(menuId);
        return result.addSuccess(data);
    }

    /**
     * 修改密码
     */
    @PostMapping("/password/change")
    @RequiresPermissions(value = ILxbAdminRights.MAIN_UPDATE_PASSWORD)
    public RespResult<String> changePassword(String oldPassword, String newPassword, String confirmPassword) {
        RespResult<String> result = new RespResult<>();
        //表单数据有效性校验
        if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword) || StringUtils.isBlank(confirmPassword)) {
            return result.addError(RespCode.ERR_400);
        }
        Administrator admin = ShiroAuthHelper.getCurrentAdmin();
        if (!newPassword.equals(confirmPassword)) {
            return result.addError("新密码与确认密码不一致");
        }
        result = adminService.changePassword(admin, oldPassword, newPassword, confirmPassword);
        logger.info("密码修改成功[userName=" + admin.getUserName() + "]");
        return result;
    }
}
